package com.seed.service.sysmanager;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.seed.commons.dbquery.PageModelForSQL;
import com.seed.commons.dbutil.DB;
import com.seed.commons.dbutil.DBBean;
import com.seed.commons.util.RandomUtil;
import com.seed.web.form.sysmanager.DepartmentForm;

@Service
public class DepartmentService implements IDepartment {

	private Log log = LogFactory.getLog(getClass());

	@Override
	public boolean saveDept(DepartmentForm dept) {
		String sql = "INSERT INTO SEED_DEPT(DeptNo,DeptName,DeptContactPeople,CreDate,OrgCodeFK) VALUES(?,?,?,TO_DATE(?,'yyyy-MM-dd'),?)";

		try {
			DB.insert(
					sql,
					new Object[] { RandomUtil.getRandomNum(8),
							dept.getDeptName(), dept.getDeptContactPeople(),
							dept.getCreDate(), dept.getOrgCodeFK()});
			return true ;
		} catch (Exception e) {
			log.info("数据插入出错：" + e.getMessage());
			log.info("执行SQL：" + sql);
		}
		return false;

	}

	@Override
	public void deleteDept(String id) {

	}

	@Override
	public void updateDept(DepartmentForm dept) {

	}

	@Override
	public DBBean queryDeptById(String id) {

		return null;
	}

	@Override
	public PageModelForSQL getScrollData(int currentPage, int lineSize) {
		
		String sql = "SELECT ORG.ORGCODE,ORG.ORGNAME,DEPT.* FROM SEED_ORG ORG,(" +
							"SELECT * FROM (" +
								"SELECT ROWNUM RN,D1.* FROM (" +
									"SELECT * FROM SEED_DEPT" +
								") D1 WHERE ROWNUM <= ?" +
							") WHERE RN > ?" +
						") DEPT WHERE ORG.ORGCODE=DEPT.ORGCODEFK ORDER BY DEPT.ORGCODEFK";
		
		String count = "SELECT COUNT(*) C FROM SEED_ORG ORG,(SELECT * FROM SEED_DEPT) DEPT WHERE ORG.ORGCODE=DEPT.ORGCODEFK";

		try {
			PageModelForSQL pm = new PageModelForSQL();
			pm.setResultList(DB.query(sql,
					new Object[] { lineSize, currentPage }));
			pm.setTotalRecord(Long.parseLong(DB.getBeanFirst(count, null)
					.getbean("c").toString()));

			return pm;
		} catch (Exception e) {
			e.printStackTrace();
			log.info("分页查询出错：" + e.getMessage());
		}
		return null;
	}

	@Override
	public List<DBBean> queryDept() {
		String sql = "SELECT * FROM SEED_DEPT" ;
		
		try {
			return DB.query(sql, null) ;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
